#import('dart:io');
#import('dart:utf');
//#import('dart:html');

List<int> lastData = const [0,0];
String ip = '192.168.1.13';
String command = "none";
WebSocketConnection globalConnection;

void webSocketServer() {
  print('starting websocket server');
  HttpServer server = new HttpServer();
  WebSocketHandler wsHandler = new WebSocketHandler();
  server.addRequestHandler((req) => req.path == "/ws", wsHandler.onRequest);
  
  wsHandler.onOpen = (WebSocketConnection conn) {
    globalConnection = conn;
    print('new connection');
    
    conn.onMessage = (message) {
      print("Received message: $message");
    };
    /*
    while(true) {
     print("Sending command: $command");
     conn.send(command);
     for(int i=0;i<100000;i++){
       //do nothing.
     }
    }
    */
    
    conn.onClosed = (int status, String reason) {
      print('closed with $status for $reason');
    };
          
    conn.onError = (e) {
      print('Error was $e');
    };
  };
  
//  server.listen('127.0.0.1', 8000);
  print('WS Server running...');  
  server.listen(ip, 8090);  
}



void tcpTest() {
  print('starting tcpip server');
 // HttpServer server = new HttpServer();
  
  
  ServerSocket ss = new ServerSocket(ip, 8000, 10);
  
//  WebSocketHandler wsHandler = new WebSocketHandler();
//  server.addRequestHandler((req) => req.path == "/ws", wsHandler.onRequest);
  
/* 
  wsHandler.onOpen = (WebSocketConnection conn) {
    print('new connection');
    
    conn.onMessage = (message) {
      print("message is $message");
      conn.send("Echo: $message");
    };
 */
  
  ss.onConnection = (Socket soc) {
    InputStream inSt = soc.inputStream;
    inSt.onData = () {
      List<int> data = inSt.read();
      //print(data);
      
      String action = codepointsToString(data);
      command = action;
      print(action);
      if (globalConnection != null) {
        globalConnection.send(action);
      }
      
      //lastData = [0, 0];
      //if (data != null && data.length > 0 && data[0] != lastData[0]) {
      //  print(data);
      //  print(codepointsToString(data));
      //  print(data[0]);
      //  lastData = data;
      //}
      
    };
  };
          
   ss.onError = (e) {
      print('Error was $e');
    };
  
    
}



main() {
  
//  webSocketTest();
  tcpTest();
  webSocketServer(); 
  
}